package com.u1zz.zeus.module.iot.service.device;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import com.u1zz.zeus.module.iot.controller.admin.device.vo.*;
import com.u1zz.zeus.module.iot.dal.dataobject.device.DeviceDO;
import com.u1zz.zeus.framework.common.pojo.PageResult;
import com.u1zz.zeus.framework.common.pojo.PageParam;
import com.u1zz.zeus.framework.common.util.object.BeanUtils;

import com.u1zz.zeus.module.iot.dal.mysql.device.DeviceMapper;

import static com.u1zz.zeus.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.u1zz.zeus.module.iot.enums.ErrorCodeConstants.*;

/**
 * 设备 Service
 *
 * @author u1zz
 */
@Service
@Validated
public class DeviceService {

    @Resource
    private DeviceMapper deviceMapper;

    public Long createDevice(DeviceSaveReqVO createReqVO) {
        // 插入
        DeviceDO device = BeanUtils.toBean(createReqVO, DeviceDO.class);
        deviceMapper.insert(device);
        // 返回
        return device.getId();
    }

    public void updateDevice(DeviceSaveReqVO updateReqVO) {
        // 校验存在
        validateDeviceExists(updateReqVO.getId());
        // 更新
        DeviceDO updateObj = BeanUtils.toBean(updateReqVO, DeviceDO.class);
        deviceMapper.updateById(updateObj);
    }

    public void deleteDevice(Long id) {
        // 校验存在
        validateDeviceExists(id);
        // 删除
        deviceMapper.deleteById(id);
    }

    private void validateDeviceExists(Long id) {
        if (deviceMapper.selectById(id) == null) {
            throw exception(DEVICE_NOT_EXISTS);
        }
    }

    public DeviceDO getDevice(Long id) {
        return deviceMapper.selectById(id);
    }

    public PageResult<DeviceDO> getDevicePage(DeviceListReqVO reqVO, PageParam pageParam) {
        return deviceMapper.selectPage(reqVO, pageParam);
    }

    public List<DeviceDO> getDeviceList(DeviceListReqVO reqVO) {
        return deviceMapper.selectList(reqVO);
    }


}